<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.css" />
    <link rel="stylesheet" type="text/css" href="../css/aui-flex.css" />
</head>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
        </div>
    </header>

    <div class="aui-content" id="divHtml" style="margin-top: 50px;">

    </div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/mqttws31.js"></script>
<script type="text/javascript">
    var port = 61623;
    var username = "";
    var password = "";
    var host = "";

    var client;

    var code; //菜单路由参数
    var list = [];


    //初始化查询仓库下拉框
    apiready = function() {
        //菜单参数
        var query = api.pageParam.query;
        code = query.code
        $api.html($api.byId("title"), "设备信号监控-" + code);

        //查询list
        getList()
    }

    //查询数据
    function getList() {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getPointList";
        var data = {
            values: {
                code: code,
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function(ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");

                //返回成功
                if (myobj.code == "0") {
                    list = eval(myobj.list);

                    //构造html
                    creatHtml();

                    //失败
                } else if (myobj.code == "1") {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                api.toast({
                    msg: JSON.stringify(err),
                    duration: 3000
                });
            }
        });
    }

    function creatHtml() {
        var str = '';
        var point;
        for (var i = 0; i < list.length; i++) {
            point = list[i].point;
            str += "<div class='aui-flex-col aui-flex-center' style='margin-top: 15px; height: 150px;color: #fff;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);'>";
            str += "    <div style='width: 40%;height: 100%;background-color: #12599a;float: left;margin-right: 1%'>";
            if (list[i].picaddr != null && list[i].picaddr != "" && list[i].picaddr != undefined) {
                str += "        <img src='" + list[i].picaddr + "' style='width: 100%; height: 100%;'>";
            } else {
                str += "        <div class='aui-text-center' style='color: red;font-size: 15px;height: 100%;padding-top: 40%;'>";
                str += "        <span >未上传设备图片</span>";
                str += "        </div>";
            }
            str += "    </div>";
            str += "    <div style='width: 59%;height: 100%;float: left;'>";
            str += "        <div class='aui-text-center' style='height: 20%;background-color: #12599a;'>";
            str += "            <span style='font-size: 15px;'>" + list[i].equipName + "</span>";
            str += "            <span style='font-size: 10px;'>(" + list[i].equipCode + ")</span>";
            str += "        </div>";
            str += "        <div class='aui-text-left' style='height: 79%;margin-top: 1%;background-color: #12599a;padding-left: 2%;font-size: 12px;overflow: auto;'>";
            for (var j = 0; j < point.length; j++) {
                str += "            <div>";
                str += "                <span>" + point[j].annotation + "：</span>";
                str += "               <span id=\"" + list[i].equipCode + "." + point[j].tagname + "\">" + point[j].tagvalue + "</span>";
                str += "            </div>";
            }
            str += "        </div>";
            str += "    </div>";
            str += "</div>";
        }
        $("#divHtml").append(str);

        //查询,mqtt服务器ip端口
        getCombox()


    }

    //查询服务器ip
    function getCombox() {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getUdiList";
        var data = {
            values: {
                code: "MQTT",
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function(ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");

                //返回成功
                if (myobj.code == "0") {
                    var mqttList = eval(myobj.list);

                    for (var i = 0; i < mqttList.length; i++) {
                        if (mqttList[i].value == 'host') {
                            host = mqttList[i].label;
                        } else if (mqttList[i].value == 'port') {
                            port = parseInt(mqttList[i].label);
                        } else if (mqttList[i].value == 'username') {
                            username = mqttList[i].label;
                        } else if (mqttList[i].value == 'password') {
                            password = mqttList[i].label;
                        }
                    }

                    //订阅mqtt
                    mqttMsg();

                    //失败
                } else if (myobj.code == "1") {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                api.toast({
                    msg: JSON.stringify(err),
                    duration: 3000
                });
            }
        });
    }

    //连接MQTT
    function mqttMsg() {
      console.log("mqttMsg11155");
        client = new Paho.MQTT.Client(host, port, '/mqtt', 'webSocket' + getUuid());
        console.log("mqttMsg22255");
        client.onConnectionLost = onConnectionLost;
        client.onMessageArrived = onMessageArrived;
        client.connect({
            userName: username,
            password: password,
            onSuccess: onConnect
        });
    }

    //连接成功后事件
    function onConnect() {
      console.log("onConnect55:"+code);
        client.subscribe(code + "/#", {
            qos: 2
        });
    }

    //断开连接
    function onConnectionLost(responseObject) {
        if (responseObject.errorCode !== 0) {
            console.log("断开连接:" + responseObject.errorMessage);
        } else {
            console.log("断开连接:" + responseObject.errorCode);
        }
    }

    //订阅后回调函数
    function onMessageArrived(message) {
      console.log("onMessageArrived55:"+JSON.stringify(message));
        var topic = message.destinationName;
        var decodedString = byteToString(message.payloadBytes);
        var map = eval("(" + decodedString + ")");
        console.log("topic55:"+topic);
console.log("onMessageArrived2255:"+JSON.stringify(map));
        //处理数据
        dealData(topic, map)
    }

    function dealData(topic, map) {
        var arr = topic.split("/");
        topic = arr[arr.length - 1];

        var index = -1
        list.filter((item, idx) => {
            if (item.equipCode == topic) {
                index = idx
                return
            }
        })

        if (index >= 0) {
            var data = this.list[index].point
            var indexNew = -1;
            for (var i in map) {
                //遍历list
                data.filter((item, idx) => {
                    //点名一样
                    if (item.tagname == i) {
                        indexNew = idx
                        return
                    }
                })
                if (indexNew >= 0) {
                    document.getElementById(topic + "." + i).innerText = map[i]
                }
                indexNew = -1;
            }
        }
    }

    function byteToString(buffer) {
        let encodedString = String.fromCodePoint.apply(
            null,
            new Uint8Array(buffer)
        )
        let decodedString = decodeURIComponent(escape(encodedString)) //没有这一步中文会乱码
        return decodedString
    }

    //生成32位随机数
    function getUuid() {
        var str = 'abcdefghijklmnopqrstuvwxyz0123456789';
        var result = '';
        for (var i = 0; i < 32; i++) {
            result += str[parseInt(Math.random() * str.length)];
        }
        return result;
    }



    //返回按钮
    function closeWin() {
        client.disconnect()
        api.closeWin({});
    }
</script>

</html>
